package com.easemob.helpdesk.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.helpdesk.bean.DispatchResult;
import com.easemob.helpdesk.bean.HouseKeeper;
import com.easemob.helpdesk.listener.OnMultiClickListener;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.utils.DisplayUtil;
import com.easemob.helpdesk.widget.CountDownProgress;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.housekeeperapp.activity.Orderdetail;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import org.w3c.dom.Text;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import retrofit2.Call;

/**
 * Created by wsj on 2018/4/23.
 */

public class ServiceOrderDialog extends BaseActivityV2 {
    private static final String TAG = "ServiceOrderDialog";

    @Override
    protected void initFindView() {
        dialog_container=findViewById(R.id.dialog_container);

        close_dialog=findViewById(R.id.close_dialog);
        dispatch_order=findViewById(R.id.dispatch_order);
        go_detail=findViewById(R.id.go_detail);
        order_type=findViewById(R.id.order_type);

        order_addr=findViewById(R.id.order_addr);
        order_time=findViewById(R.id.order_time);
        order_content=findViewById(R.id.order_content);
        order_addr_text=findViewById(R.id.order_addr_text);

        order_content_text=findViewById(R.id.order_content_text);
        order_time_text=findViewById(R.id.order_time_text);
        time_count=findViewById(R.id.time_count);
        countdownProgress=findViewById(R.id.countdownProgress);

        divider=findViewById(R.id.divider);
        orderPrice=findViewById(R.id.order_price);
        orderPriceContainer=findViewById(R.id.order_price_container);


    }

    public RelativeLayout dialog_container;
    public ImageView close_dialog;
    public ImageView dispatch_order;
    public TextView go_detail;
    public ImageView order_type;

    // key
    public TextView order_addr;

    public TextView order_time;

    public TextView order_content;

    // value
    public TextView order_addr_text;

    public TextView order_content_text;

    public TextView order_time_text;

    public TextView time_count;

    public CountDownProgress countdownProgress;

    View divider;
    TextView orderPrice;
    View orderPriceContainer;

    private Handler mHandler = new Handler();

    /**
     * 加载提示Dialog
     */
    public Dialog pd = null;

    private SoundPool mSoundPlayer;

    private CountDownTimer timer;

    private Vibrator vibrator;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_service_order);
        initFindView();

        this.setFinishOnTouchOutside(false);

        Intent intent = getIntent();
        String extras = intent.getStringExtra("extras");
        final JsonObject order = CommonUtils.parseJson(extras);
        int outerwidth = getResources().getDisplayMetrics().widthPixels;
        ViewGroup.LayoutParams layoutlp = dialog_container.getLayoutParams();
        layoutlp.width = outerwidth - 95;
        dialog_container.setLayoutParams(layoutlp);

        close_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isFinishing() && !isDestroyed()){
                    finish();
                }
            }

        });

        go_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainApplication app = (MainApplication)getApplication();
                WritableMap map = new WritableNativeMap();
                map.putString("orderId", String.valueOf(order.get("id").getAsLong()));
                app.getEventEmitter().sendNavigatorEvent("orderDetail", map);
            }
        });

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            if(order.get("service_time") != null){
                Date service_date = sdf.parse(order.get("service_time").getAsString());
                Date cur_date = new Date();
                if(service_date.getTime() - cur_date.getTime()<0){
                    time_count.setText("0");
                }else{
                    long mm = (service_date.getTime() - cur_date.getTime())/1000/60;
                    time_count.setText(String.valueOf(mm));
                }
            }

            if (order.get("serviceFee_pay_status") != null){
                if ( order.get("serviceFee_pay_status").getAsInt() == 0){//没有支付订单
                    orderPriceContainer.setVisibility(View.GONE);
                    divider.setVisibility(View.GONE);
                }else {
                    orderPriceContainer.setVisibility(View.VISIBLE);
                    divider.setVisibility(View.VISIBLE);
                    orderPrice.setText(order.get("order_price").getAsBigDecimal().setScale(2).doubleValue()+"");
                }
            }else {
                orderPriceContainer.setVisibility(View.GONE);
                divider.setVisibility(View.GONE);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        String service_type = order.get("service_type").getAsString();

        if("buy".equals(service_type)){
            order_type.setImageResource(R.drawable.hk_service_buy2x);
            order_addr.setText("购买物品");
            order_content.setText("收");
            order_time.setText("备注");

            order_addr_text.setText(order.get("obj_name").getAsString());
            order_content_text.setText(order.get("to_address").getAsString());
            order_time_text.setText(order.get("remarks").getAsString().equals("")?"无":order.get("remarks").getAsString());

        }else if("send".equals(service_type)){
            order_type.setImageResource(R.drawable.hk_service_send2x);
            order_addr.setText("寄");
            order_content.setText("收");
            order_time.setText("备注");

            order_addr_text.setText(order.get("from_address").getAsString());
            order_content_text.setText(order.get("to_address").getAsString());
            order_time_text.setText(order.get("remarks").getAsString().equals("")?"无":order.get("remarks").getAsString());

        }else if("express".equals(service_type)){
            order_type.setImageResource(R.drawable.hk_service_express2x);

            order_addr_text.setText(order.get("to_address").getAsString());
            order_content_text.setText(order.get("express_service_content").getAsString());
            order_time_text.setText(order.get("service_time").getAsString());

        }else if("lockkey".equals(service_type)){
            order_type.setImageResource(R.drawable.hk_service_lockkey2x);

            order_addr_text.setText(order.get("to_address").getAsString());
            order_content_text.setText(order.get("lockkey_service_content").getAsString());
            order_time_text.setText(order.get("service_time").getAsString());


        }else if("other".equals(service_type)){
            order_type.setImageResource(R.drawable.hk_service_other2x);

            order_addr_text.setText(order.get("to_address").getAsString());
            order_content_text.setText(order.get("other_service_content").getAsString());
            order_time_text.setText(order.get("service_time").getAsString());
        }else if ("nursing".equals(service_type)){
            order_type.setImageResource(R.drawable.hk_service_nursing2x);

            order_addr_text.setText(order.get("to_address").getAsString());
            order_content_text.setText(order.get("other_service_content").getAsString());
            order_time_text.setText(order.get("service_time").getAsString());
        }


        // 设置类型

        // 5秒倒计时
        countdownProgress.setCountdownTime(5*1000);
        dispatch_order.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                loadRob(order.get("id").getAsLong());
            }
        });

        countdownProgress.startCountDownTime(new CountDownProgress.OnCountdownFinishListener() {
            @Override
            public void countdownFinished() {
                if(!isFinishing() && !isDestroyed()){
                    finish();
                }
            }
        });


        vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);

//        if(vibrator.hasVibrator()){
//            vibrator.cancel();
//        }

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (MainApplication.getInstance().isNotiAlertVibrateStatus()) {
                    vibrator.cancel();
                    //震动
                    long[] pattern = new long[] { 0, 180, 80, 120 };
                    vibrator.vibrate(pattern, -1);
                }

                if(!MainApplication.getInstance().isNotiAlertSoundStatus()){
                    return;
                }

                if(mSoundPlayer != null){
                    mSoundPlayer.release();
                    mSoundPlayer = null;
                }

                mSoundPlayer = new SoundPool(10,
                        AudioManager.STREAM_NOTIFICATION, 5);
                mSoundPlayer.load(ServiceOrderDialog.this, R.raw.order_sound, 1);
                mSoundPlayer.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                    @Override
                    public void onLoadComplete(SoundPool soundPool, int sampleId,
                                               int status) {
                        mSoundPlayer.play(1, 1, 1, 0, 0, 1);
                    }
                });
            }
        });

    }

    public void showLoading() {
        //显示登录提示对话框
        if(!isFinishing()){
            pd = DialogUtils.getLoadingDialog(MainApplication.getInstance().getTopActivity(), "抢单中...");
            pd.show();
        }
    }

    public void hideLoading() {
        if(!isFinishing() && pd != null && pd.isShowing()){
            pd.dismiss();
        }
    }


    @Override
    protected void onDestroy() {
        hideLoading();
        if(mSoundPlayer != null){
            mSoundPlayer.release();
        }

        super.onDestroy();
    }


    private void loadRob(long id) {

        showLoading();

        ApiService apiService = HKHttpUtils.getApiService();
        Call<BaseResponse<Boolean>> call = apiService.rotOrder(MainActivity.ticket, String.valueOf(MainActivity.userId), String.valueOf(id));
        call.enqueue(new HKResponseResultCallBack<Boolean>() {
            @Override
            public void onSuccess(final Boolean aBoolean) {
                new CountDownTimer(1000, 500) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }
                    @Override
                    public void onFinish(){
                        if(!aBoolean){
                            Dialog dialog_err = DialogUtils.getFailOrderDialog(MainApplication.getInstance().getTopActivity(), "");
                            dialog_err.show();
                        }else{
                            MainApplication.getInstance().gotoMainActivity();
                            if(MainActivity.userRole == 0){
                                if (MainActivity.instance != null) {
                                    MainActivity.instance.selectTab(2);
                                }
                            }else if(MainActivity.userRole == 2){
                                if (MainActivity.instance != null) {
                                    MainActivity.instance.selectTab(0);
                                }
                            }

                            MainApplication.getInstance().getEventEmitter().sendEvent("gotoPage");
                            MainApplication.getInstance().getEventEmitter().sendEvent("order.onload");
                            Toast.makeText(MainApplication.getInstance().getTopActivity(), "抢单成功", Toast.LENGTH_SHORT).show();
                        }
                    }
                }.start();

                finish();
            }

            @Override
            public void onGetDataFailed(int cd, final String msg) {
                new CountDownTimer(1000, 500) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }
                    @Override
                    public void onFinish(){
                        Dialog dialog_err = DialogUtils.getFailOrderDialog(MainApplication.getInstance().getTopActivity(), msg);
                        dialog_err.show();
                    }
                }.start();

                finish();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                new CountDownTimer(1000, 500) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }
                    @Override
                    public void onFinish(){
                        Dialog dialog_err = DialogUtils.getFailOrderDialog(MainApplication.getInstance().getTopActivity(), "");
                        dialog_err.show();
                    }
                }.start();

                finish();
            }
        });

//        OkHttpClient okHttpClient = new OkHttpClient();
//        RequestBody body = new FormBody.Builder()
//                .add("id", String.valueOf(id))
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "order/rob")
//                .header("user_id", String.valueOf(MainActivity.userId))
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        hideLoading();
//                        new CountDownTimer(1000, 500) {
//                            @Override
//                            public void onTick(long millisUntilFinished) {
//
//                            }
//                            @Override
//                            public void onFinish(){
//                                Dialog dialog_err = DialogUtils.getFailOrderDialog(MainApplication.getInstance().getTopActivity(), "");
//                                dialog_err.show();
//                            }
//                        }.start();
//
//                        finish();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call,Response response) throws IOException {
//
//                String res = response.body().string();
//                final JsonObject result = CommonUtils.parseJson(res);
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        hideLoading();
//
//                        new CountDownTimer(1000, 500) {
//                            @Override
//                            public void onTick(long millisUntilFinished) {
//
//                            }
//                            @Override
//                            public void onFinish(){
//                                if(!result.get("data").getAsBoolean()){
//                                    Dialog dialog_err = DialogUtils.getFailOrderDialog(MainApplication.getInstance().getTopActivity(), "");
//                                    dialog_err.show();
//                                }else{
//                                    MainApplication.getInstance().gotoMainActivity();
//                                    if(MainActivity.instance.userRole == 0){
//                                        MainActivity.instance.selectTab(2);
//                                    }else if(MainActivity.instance.userRole == 2){
//                                        MainActivity.instance.selectTab(0);
//                                    }
//
//                                    MainApplication.getInstance().getEventEmitter().sendEvent("gotoPage");
//                                    MainApplication.getInstance().getEventEmitter().sendEvent("order.onload");
//                                    Toast.makeText(MainApplication.getInstance().getTopActivity(), "抢单成功", Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        }.start();
//
//                        finish();
//
//                    }
//                });
//
//            }
//        });

    }
}
